const SocksClient  = require('socks').SocksClient;
const SSHClient    = require('ssh2').Client;

const ppy_ssh = async (ctx) => {
  const con = new SSHClient();
  let shell_stream = null;
  let ops = ctx.state.opts;
  
  if(ops.use_s5proxy == true){
    SocksClient.createConnection(ops, (err, info) => {
      if (!err) {
        con.connect({
          sock: info.socket,
          username: ops.account.username,
          password: ops.account.password
        });
      }else{
        ctx.websocket.send('socks5 连接失败\n\r');
        return;
      }
    });
  }else{
    con.connect({
      host: ops.destination.host,
      port: ops.destination.port,
      username: ops.account.username,
      password: ops.account.password
    });
  }

  con.on('ready', () => {
    console.log('ssh_client :: ready');
    con.shell((err, stream) => {
        if (err) {
            console.log('err over ');
            ctx.websocket.send('ssh_client :: ready :: error over.\n\r');
            return;
        }
        shell_stream = stream;

        stream.on('data', (data) => {
            ctx.websocket.send(data);
        }).on('close', () => {
            shell_stream = null;
            console.log('success over ')
            ctx.websocket.send('ssh_client :: data :: success over.\n\r');
            ctx.websocket.close()
        }).stderr.on('data', (data) => {
            shell_stream = null;
            console.log('stderr: ' + data);
            ctx.websocket.send('ssh_client :: data ::stderr.\n\r');
            ctx.websocket.close()
        });
    });
  });
 
  con.on('error', (err) => {
    console.log('ssh_client :: error :: ' + err);
    ctx.websocket.send('ssh_client :: error :: ' + err + '.\n\r');
  });
  
  con.on('end', () => {
    console.log('ssh_client :: end');
    ctx.websocket.send('ssh_client :: end.\n\r');
  });
  
  con.on('close', (had_error) => {
    console.log('ssh_client :: close');
  });

  ctx.websocket.on('message', (data) => {
    if(shell_stream != null){
      shell_stream.write(data);
    }
  });

  ctx.websocket.on('close', () => {
      console.log('ssh_ws :: close.');
      con.end();
  });
}

module.exports = {
    ppy_ssh
}